/**
 * 用户管理模块
 */
const router = require('koa-router')();
const jwt = require('../utils/jwt');
const menuDB = require('../models/menuSchema');
const userDB = require('../models/userSchema');
const roleDB = require('../models/roleSchema');
const userIdDB = require('../models/userIdSchema');
const util = require('../utils/util');
const md5 = require('md5');

router.prefix('/user');

// 用户登录接口
router.post('/login', async (ctx) => {
  try {
    let { userName, userPwd } = ctx.request.body;
    // 指定返回的字段
    const user = await userDB.findOne({ userName, userPwd: md5(userPwd) }, 'userId userName userEmail state role deptId roleList');
    if (user) {
      let res = user._doc;
      let token = jwt.sign(res);
      res.token = token;
      ctx.body = util.success(res);
    } else {
      ctx.body = util.fail('账号或密码错误');
    }
  } catch (err) {
    ctx.body = util.fail(err);
  }
});

// 查询所有的角色列表
router.get('/allList', async (ctx) => {
  try {
    let list = await userDB.find({}, 'userId userName userEmail');
    ctx.body = util.success(list);
  } catch (error) {
    ctx.body = util.fail(`查询失败：${error.stack}`);
  }
});

// 查询用户列表
router.get('/list', async (ctx) => {
  let { userId, userName, state } = ctx.request.query;
  let { page, skipIndex } = util.pager(ctx.request.query);
  let params = {};
  if (userId) params.userId = userId;
  if (userName) params.userName = userName;
  if (state && state != '0') params.state = state;
  const query = userDB.find(params, { userPwd: 0 });
  const list = await query.skip(skipIndex).limit(page.pageSize);
  const total = await userDB.countDocuments(params);
  ctx.body = util.success({ list, page: { ...page, total } });
});

// 删除用户
router.post('/delete', async (ctx) => {
  let { userIds } = ctx.request.body;
  // 软删除  标记为离职
  const res = await userDB.updateMany({ userId: { $in: userIds } }, { state: 2 });
  if (res.nModified) {
    ctx.body = util.success({ nModified: res.nModified }, `删除成功，本次删除 ${res.nModified} 条数据`);
    return;
  }
  ctx.body = util.fail();
});

// 编辑或添加用户
router.post('/operate', async (ctx) => {
  let { userId, userEmail, userName, mobile, state, job, roleList, deptId, action } = ctx.request.body;
  // 必填参数校验
  if (!userName || !userEmail || !deptId || !action) {
    ctx.body = util.failParam();
    return;
  }
  // 新增处理
  if (action === 'add') {
    const res = await userDB.findOne({ userEmail }, '_id userName userEmail');
    if (res) {
      ctx.body = util.fail(`用户邮箱重复：${res.userName} - ${res.userEmail}`);
    } else {
      const { sequence_value } = await userIdDB.findOneAndUpdate({ _id: 'userId' }, { $inc: { sequence_value: 1 } }, { new: true });
      let user = new userDB({ userId: sequence_value, userPwd: md5('123456'), userEmail, role: 1, userName, mobile, state, job, roleList, deptId });
      user.save();
      ctx.body = util.success({}, '创建用户成功');
    }
    return;
  }
  // 编辑处理
  if (action === 'edit') {
    // 后端都不可以改用户名和邮箱
    const res = await userDB.updateOne({ userId }, { job, roleList, deptId, state, mobile });
    // const res = await userDB.findOneAndUpdate({ userId }, { job, roleList, deptId, state, mobile });
    ctx.body = util.success({}, '编辑成功');
    return;
  }
  // 走到这里就抛出异常
  ctx.body = util.fail();
});

// 获取用户可以访问的菜单
router.get('/userMenu', async (ctx) => {
  // 获取token
  // let authorization = ctx.request.headers.authorization;
  // let token = authorization.split(' ')[1];
  // let { data } = jwt.verify(token);
  // 获取token 信息
  let data = util.getTokenInfo(ctx.request.headers.authorization);
  // 获取用户的 菜单访问权限
  let menuList = await getUserMenuList(data.role, data.roleList);
  // 菜单中过滤出来按钮
  let actionList = getActionList(JSON.parse(JSON.stringify(menuList)));
  ctx.body = util.success({ menuList, actionList });
});

async function getUserMenuList(userRole, roleKeys) {
  let menuList = [];
  // 管理员直接全量返回
  if (userRole == 0) {
    menuList = (await menuDB.find({})) || [];
  } else {
    // 普通用户需要获取权限
    let roleList = await roleDB.find({ _id: { $in: roleKeys } });
    // 获取所有能查看的 menuId
    let permissionList = [];
    roleList.map((role) => {
      let { checkedKeys, halfCheckedKeys } = role.permissionList;
      permissionList = [...permissionList, ...checkedKeys, ...halfCheckedKeys];
    });
    permissionList = [...new Set(permissionList)];
    // 查找出能查看的menu
    menuList = await menuDB.find({ _id: { $in: permissionList } });
  }
  // 将 menuList 组装成树结构
  return util.getTreeMenu(menuList, null, []);
}

function getActionList(menuList) {
  let actionList = [];
  const deepAction = (arr) => {
    while (arr.length) {
      let item = arr.pop();
      if (item.action) {
        item.action.map((a) => {
          actionList.push(a.menuCode);
        });
      }
      if (item.children && !item.action) {
        deepAction(item.children);
      }
    }
  };
  deepAction(menuList);
  return actionList;
}

module.exports = router;
